var tvRemote = function(words) {
    var width = 8;
    var height = 6;
    const dist = (A, B) => {
        var d = Math.abs(A[0] - B[0]) + Math.abs(A[1] - B[1]) + 1;
        var dx = Math.abs(A[1] - B[1]);
        var dy = Math.abs(A[0] - B[0]);
        var a = width - dx + dy + 1;
        var b = dx + height - dy + 1;
        var c = width - dx + height - dy + 1;
        return Math.min(...[a, b, c, d])
    }
    var kb = {'a': [0, 0],'b': [0, 1],'c': [0, 2],'d': [0, 3],'e': [0, 4],'1': [0, 5],'2': [0, 6],'3': [0, 7],'f': [1, 0],
        'g': [1, 1],'h': [1, 2],'i': [1, 3],'j': [1, 4],'4': [1, 5],'5': [1, 6],'6': [1, 7],'k': [2, 0],'l': [2, 1],'m': [2, 2],
        'n': [2, 3],'o': [2, 4],'7': [2, 5],'8': [2, 6],'9': [2, 7],'p': [3, 0],'q': [3, 1],'r': [3, 2],'s': [3, 3],'t': [3, 4],
        '.': [3, 5],'@': [3, 6],'0': [3, 7],'u': [4, 0],'v': [4, 1],'w': [4, 2],'x': [4, 3],'y': [4, 4],'z': [4, 5],'_': [4, 6],
        '/': [4, 7],'aA': [5, 0],'SP': [5, 1]};
    var isLower = true;
    var cur_pos = [0, 0];
    var d = 0
    for (c of words) {
        if (/[a-z]/i.test(c) && /[a-z]/g.test(c) != isLower) {
            //go to shift first
            isLower = !isLower;
            d += dist(cur_pos, kb['aA']);
            cur_pos = kb['aA'];
        }
        next_pos = (/\s/.test(c) ? kb['SP'] : kb[c.toLowerCase()]);
        d += dist(next_pos, cur_pos);
        cur_pos = next_pos;
    }
    return d;
}
